/**
 * 设备设置命令API接口
 * 
 * @author lawrencehj
 * @date 2021年2月2日
 */

package com.genersoft.iot.vmp.vmanager.gb28181.device;

import com.alibaba.fastjson.JSONObject;
import com.genersoft.iot.vmp.common.ResultCode;
import com.genersoft.iot.vmp.gb28181.bean.Device;
import com.genersoft.iot.vmp.gb28181.transmit.callback.DeferredResultHolder;
import com.genersoft.iot.vmp.gb28181.transmit.callback.RequestMessage;
import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommander;
import com.genersoft.iot.vmp.gb28181.utils.NumericUtil;
import com.genersoft.iot.vmp.gb28181.utils.SignUtil;
import com.genersoft.iot.vmp.storager.IVideoManagerStorager;
import com.genersoft.iot.vmp.vmanager.bean.WVPResult;
import com.genersoft.iot.vmp.vmanager.gb28181.device.bean.DeviceParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;

import javax.sip.message.Response;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "国标设备配置")
@CrossOrigin
@RestController
@RequestMapping("/api/device/config")
public class DeviceConfig {

    private final static Logger logger = LoggerFactory.getLogger(DeviceQuery.class);

    @Autowired
    private IVideoManagerStorager storager;

    @Autowired
    private SIPCommander cmder;

    @Autowired
    private DeferredResultHolder resultHolder;

	/**
	 * 看守位控制命令API接口
	 * @param deviceId 设备ID
	 * @param channelId 通道ID
	 * @param name 名称
	 * @param expiration 到期时间
	 * @param heartBeatInterval 心跳间隔
	 * @param heartBeatCount 心跳计数
	 * @return
	 */
	@ApiOperation("基本配置设置命令")
	@GetMapping("/basicParam/{deviceId}")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "deviceId", value ="设备ID" ,dataTypeClass = String.class),
			@ApiImplicitParam(name = "channelId", value ="通道ID",dataTypeClass = String.class ),
			@ApiImplicitParam(name = "name", value ="名称" ,dataTypeClass = String.class),
			@ApiImplicitParam(name = "expiration", value ="到期时间" ,dataTypeClass = String.class),
			@ApiImplicitParam(name = "heartBeatInterval", value ="心跳间隔" ,dataTypeClass = String.class),
			@ApiImplicitParam(name = "heartBeatCount", value ="心跳计数" ,dataTypeClass = String.class),
	})
	public DeferredResult<ResponseEntity<String>> homePositionApi(@PathVariable String deviceId,
                                                                @RequestParam(required = false) String channelId,
                                                                @RequestParam(required = false) String name,
																@RequestParam(required = false) String expiration,
																@RequestParam(required = false) String heartBeatInterval,
                                                                @RequestParam(required = false) String heartBeatCount) {
        if (logger.isDebugEnabled()) {
			logger.debug("报警复位API调用");
		}
		Device device = storager.queryVideoDevice(deviceId);
		cmder.deviceBasicConfigCmd(device, channelId, name, expiration, heartBeatInterval, heartBeatCount, event -> {
			Response response = event.getResponse();
			RequestMessage msg = new RequestMessage();
			msg.setId(DeferredResultHolder.CALLBACK_CMD_DEVICECONFIG + (StringUtils.isEmpty(channelId) ? deviceId : channelId));
			msg.setData(String.format("设备配置操作失败，错误码： %s, %s", response.getStatusCode(), response.getReasonPhrase()));
			resultHolder.invokeResult(msg);
		});
        DeferredResult<ResponseEntity<String>> result = new DeferredResult<ResponseEntity<String>>(3 * 1000L);
		result.onTimeout(() -> {
			logger.warn(String.format("设备配置操作超时, 设备未返回应答指令"));
			// 释放rtpserver
			RequestMessage msg = new RequestMessage();
			msg.setId(DeferredResultHolder.CALLBACK_CMD_DEVICECONFIG + (StringUtils.isEmpty(channelId) ? deviceId : channelId));
			JSONObject json = new JSONObject();
			json.put("DeviceID", deviceId);
			json.put("Status", "Timeout");
			json.put("Description", "设备配置操作超时, 设备未返回应答指令");
			msg.setData(json); //("看守位控制操作超时, 设备未返回应答指令");
			resultHolder.invokeResult(msg);
		});
		resultHolder.put(DeferredResultHolder.CALLBACK_CMD_DEVICECONFIG + (StringUtils.isEmpty(channelId) ? deviceId : channelId), result);
		return result;
	}


	@ApiOperation("设备参数设置")
	@PostMapping({"/update"})
	@ApiImplicitParams({
			@ApiImplicitParam(name = "DeviceParam", value ="设备参数" ,dataTypeClass = DeviceParam.class)
	})
	public DeferredResult<ResponseEntity<String>> deviceParamUpdate(DeviceParam deviceParam) {
		if (logger.isDebugEnabled()){
			logger.debug("设备参数设置API调用");
		}
		DeferredResult<ResponseEntity<String>> result = new DeferredResult(Long.valueOf(3000L));
		WVPResult wvpResult = new WVPResult();
		String deviceId = deviceParam.getDeviceId();
		String name = deviceParam.getName();
		if (StringUtils.isEmpty(deviceId)) {
			this.resultHolder.put("SIGN_CHECK" + deviceId, result);
			RequestMessage msg = new RequestMessage();
			msg.setId("CALLBACK_DEVICECONTROL" + deviceId);
			wvpResult.setValue(ResultCode.PARAMS_ERROR);
			msg.setData(wvpResult);
			this.resultHolder.invokeResult(msg);
		}
		Device device = this.storager.queryVideoDevice(deviceId);
		/*Map<String, String> signParam = new HashMap<>();
		signParam.put("deviceId", deviceId);
		signParam.put("name", name);
		signParam.put("expiration", deviceParam.getExpiration());
		signParam.put("heartBeatInterval", deviceParam.getHeartBeatInterval());
		signParam.put("heartBeatCount", deviceParam.getHeartBeatCount());
		signParam.put("volume", deviceParam.getVolume());
		signParam.put("alarmFlag", deviceParam.getAlarmFlag());
//		signParam.put("topLeft", deviceParam.getTopLeft());
//		signParam.put("bottomRight", deviceParam.getBottomRight());

		signParam.put("pointCount", deviceParam.getPointCount()+"");
		signParam.put("point1", deviceParam.getPoint1());
		signParam.put("point2", deviceParam.getPoint2());
		signParam.put("point3", deviceParam.getPoint3());
		signParam.put("point4", deviceParam.getPoint4());
		signParam.put("point5", deviceParam.getPoint5());
		signParam.put("sensitivity", deviceParam.getSensitivity());
		signParam.put("photoUploadURL", deviceParam.getPhotoUploadURL());
		signParam.put("timerFlag", deviceParam.getTimerFlag()+"");
		signParam.put("timerType", deviceParam.getTimerType());
		signParam.put("guardTime", deviceParam.getGuardTime()+"");
		signParam.put("resetGuardTime", deviceParam.getResetGuardTime()+"");
		signParam.put("time", deviceParam.getTime());
		if (!"testSign".equals(deviceParam.getSign()) && !SignUtil.signCheck(signParam, device.getPrivateKey(), deviceParam.getSign())) {
			this.resultHolder.put("SIGN_CHECK" + deviceId, result);
			RequestMessage msg = new RequestMessage();
			msg.setId("SIGN_CHECK" + deviceId);
			wvpResult.setValue(ResultCode.SIGN_ERROR);
			msg.setData(wvpResult);
			this.resultHolder.invokeResult(msg);
		}*/
		this.cmder.deviceBasicConfig(device, deviceParam, event -> {
			Response response = event.getResponse();
			RequestMessage msg = new RequestMessage();
			msg.setId("CALLBACK_DEVICECONFIG" + deviceId);
			wvpResult.setCode(response.getStatusCode());
			wvpResult.setMsg(response.getReasonPhrase());
			msg.setData(wvpResult);
			this.resultHolder.invokeResult(msg);
		});
		result.onTimeout(() -> {
			logger.warn(String.format("设备配置操作超时, 设备未返回应答指令 %s", deviceId));
			RequestMessage msg = new RequestMessage();
			msg.setId("CALLBACK_DEVICECONFIG" + deviceId);
			wvpResult.setCode(ResultCode.ERROR_CODE.getCode());
			wvpResult.setMsg("设备配置操作超时, 设备未返回应答指令");
			msg.setData(wvpResult);
			this.resultHolder.invokeResult(msg);
		});
		this.resultHolder.put("CALLBACK_DEVICECONFIG" + deviceId, result);

		/* 修改为先通过设备信息查询，再修改数据库
		Device deviceInfo = new Device();
		if(!StringUtils.isEmpty(deviceParam.getVolume()) && NumericUtil.isInteger(deviceParam.getVolume()) &&
				Integer.valueOf(deviceParam.getVolume()).intValue() > 0){
			deviceInfo.setVolume(Integer.valueOf(deviceParam.getVolume()));

		}
		if(!StringUtils.isEmpty(deviceParam.getAlarmFlag()) && NumericUtil.isInteger(deviceParam.getAlarmFlag())){
			deviceInfo.setAlarmFlag(Integer.valueOf(deviceParam.getAlarmFlag()));
			if("1".equals(deviceParam.getAlarmFlag())){
				deviceInfo.setTopLeft(deviceParam.getTopLeft());
				deviceInfo.setBottomRight(deviceParam.getBottomRight());
			}
		}
		deviceInfo.setSensitivity(deviceParam.getSensitivity());
*/

		//修改定时布撤防参数
		if(deviceParam.getTimerFlag() !=null) {
			Device deviceInfo = new Device();
			deviceInfo.setDeviceId(deviceId);
			deviceInfo.setTimerFlag(deviceParam.getTimerFlag());
			if(deviceParam.getGuardTime()!=null) {
				deviceInfo.setGuardTime(deviceParam.getGuardTime());
			}
			if(deviceParam.getResetGuardTime()!=null) {
				deviceInfo.setResetGuardTime(deviceParam.getResetGuardTime());
			}
			storager.updateDevice(deviceInfo);
		}
		//查询设备信息
		cmder.deviceInfoQuery(device);


		return result;
	}


	@ApiOperation("设备参数设置")
	@PostMapping({"/updateConfig"})
	@ApiImplicitParams({
			@ApiImplicitParam(name = "DeviceParam", value ="设备参数" ,dataTypeClass = DeviceParam.class)
	})
	public DeferredResult<ResponseEntity<String>> deviceParamUpdateForJson(@RequestBody DeviceParam deviceParam) {
		return this.deviceParamUpdate(deviceParam);
	}

	/**
	 * 设备配置查询请求API接口
	 * @param deviceId 设备ID
	 * @param configType 配置类型
	 * @param channelId 通道ID
	 * @return
	 */
	@ApiOperation("设备配置查询请求")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "deviceId", value ="设备ID" ,dataTypeClass = String.class),
			@ApiImplicitParam(name = "channelId", value ="通道ID" ,dataTypeClass = String.class),
			@ApiImplicitParam(name = "configType", value ="配置类型" ,dataTypeClass = String.class),
	})
	@GetMapping("/query/{deviceId}/{configType}")
    public DeferredResult<ResponseEntity<String>> configDownloadApi(@PathVariable String deviceId, 
                                                                @PathVariable String configType,
                                                                @RequestParam(required = false) String channelId) {
		if (logger.isDebugEnabled()) {
			logger.debug("设备状态查询API调用");
		}
		Device device = storager.queryVideoDevice(deviceId);
		cmder.deviceConfigQuery(device, channelId, configType, event -> {
			Response response = event.getResponse();
			RequestMessage msg = new RequestMessage();
			msg.setId(DeferredResultHolder.CALLBACK_CMD_CONFIGDOWNLOAD + (StringUtils.isEmpty(channelId) ? deviceId : channelId));
			msg.setData(String.format("获取设备配置失败，错误码： %s, %s", response.getStatusCode(), response.getReasonPhrase()));
			resultHolder.invokeResult(msg);
		});
        DeferredResult<ResponseEntity<String>> result = new DeferredResult<ResponseEntity<String >> (3 * 1000L);
		result.onTimeout(()->{
			logger.warn(String.format("获取设备配置超时"));
			// 释放rtpserver
			RequestMessage msg = new RequestMessage();
			msg.setId(DeferredResultHolder.CALLBACK_CMD_CONFIGDOWNLOAD + (StringUtils.isEmpty(channelId) ? deviceId : channelId));
			msg.setData("Timeout. Device did not response to this command.");
			resultHolder.invokeResult(msg);
		});
		resultHolder.put(DeferredResultHolder.CALLBACK_CMD_CONFIGDOWNLOAD + (StringUtils.isEmpty(channelId) ? deviceId : channelId), result);
		return result;
	}

}
